<template>
  <div class="padding_20">
    <div class="grid-content bg-purple-light">
      <div class="righttitle">{{ title }}分类</div>

      <el-form ref="form" :model="form" label-width="80px" style="margin-top:30px">
        <el-form-item label="父类" v-if="isshow">
          <el-cascader :disabled="disabled" @change="changefathername" v-model="form.fathername" :options="options" :props="defaultProps" clearable style="width:40%"></el-cascader>
        </el-form-item>
        <el-form-item label="分类名称">
          <el-input v-model="form.name" style="width:40%" placeholder="请输入分类名称" maxlength="20" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="分类编码">
          <el-input v-model.trim="form.categoryNo" style="width:40%" placeholder="请输入分类编码" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="排序">
          <el-input v-model="form.sort" style="width:40%" placeholder="请输入4位之内纯数字" maxlength="4" show-word-limit></el-input>
        </el-form-item>
        
        <template v-if="form.fathername && form.fathername.length">
          <el-form-item label="分类图片" v-if="ispic">
            <upload ref="classimg" :url="imgurl" @onsuccess="aaa" />
          </el-form-item>
          <el-form-item v-if="ispic">
            <div class="tags">图片尺寸建议100*100正方形,最好为透明底的png图片</div>
          </el-form-item>
          <el-form-item label="绑定属性" class="bdd" v-if="isbd">
            <div class="hx">
              <el-tag v-for="tag in tags" :key="tag.name" closable :type="tag.type" @close="handleClose(tag)" style="margin-left:5px">{{ tag.name }}</el-tag>
            </div>
            <el-button type="primary" style="display:inline-block;margin-left:20px" @click="selectad">选择属性</el-button>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="savedate">确定</el-button>
          <!-- <el-button>取消</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="绑定数据" :visible.sync="dialogTableVisible">
      <!-- <el-form>
        <el-form-item label="属性名称">
          <el-input v-model="classname" style="width:40%" placeholder="请输入属性名称"></el-input>
          <el-button type="primary" style="margin-left:20px">查询</el-button>
        </el-form-item>
      </el-form> -->
      <el-table @select-all="allselect" :data="gridData" ref="multipleTable" :header-cell-style="{ background: '#eef1f6', color: '#606266' }" @select="select">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" label="序号" width="150" align="center"></el-table-column>
        <el-table-column property="propertyName" label="属性名称" width="200"></el-table-column>
        <el-table-column property="propertyName" label="属性描述"></el-table-column>
      </el-table>
      <el-pagination class="fy" background :page-size="10" layout="prev, pager, next,total" :total="pagecount" @current-change="paging"> </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getContenttree, getclassname, saveclass, editclass, removeclass, getbyid } from '@/api/storeclass'
import { getcontents } from '@/api/tab'
import upload from '@/components/upload-elementui'
export default {
  components: {
    upload
  },
  data() {
    return {
      disabled: false,
      imgurl: '',
      pagecount: 0,
      commonurl: `${process.env.VUE_APP_FILE_URL}/`,
      title: '添加',
      isshow: true,
      ispic: true,
      categoryid: '',
      allselectitem: [],
      alllevel: '',
      parentId: 0,
      iseditsave: false,
      isaddsave: false,
      form: {
        name: '',
        categoryNo: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        sort: '',
        fathername: []
      },
      isbd: true,
      classname: '',
      dialogImageUrl: '',
      dialogVisible: false,
      options: [],
      // addtrue: true,
      tags: [
        // { name: '标签一', type: '' },
        // { name: '标签二', type: 'success' },
        // { name: '标签三', type: 'info' },
        // { name: '标签四', type: 'warning' },
        // { name: '标签五', type: 'danger' }
      ],
      colorArray: ['success', 'info', 'warning', 'danger'],
      defaultProps: {
        children: 'goodsCategoryModelList',
        label: 'title',
        value: 'id',
        checkStrictly: true
      },
      gridData: [],
      dialogTableVisible: false
    }
  },
  created() {
    //   渲染选择父节点列表
    this.gettree()
    //js方法：点击文字时自动选中radio标签
    setInterval(function() {
      document.querySelectorAll('.el-cascader-node__label').forEach(el => {
        el.onclick = function() {
          if (this.previousElementSibling) this.previousElementSibling.click()
        }
      })
    }, 1000)
  },

  methods: {
    // 改变父类名称时触发
    changefathername(data) {
      console.log(data)
      // 如果选择的长度是0则是添加的第一类,所以level是1
      if (data.length == 0) {
        this.alllevel = 1
        //  当没有选择级联选择器选择父类名称时,默认穿父类ID为0
        this.parentId = 0
      }
      if (data.length == 1) {
        this.alllevel = 2
        this.parentId = data[0]
      }
      if (data.length == 2) {
        this.alllevel = 3
        this.parentId = data[1]
      }
      console.log(99999)
    },
    // 选中弹出框里的列表选中框
    select(selection, row) {
      console.log(selection)
      console.log(row)
      let _arr = []
      selection.forEach(item => {
        let obj = {}
        obj.propertyId = item.id
        obj.name = obj.propertyName = item.propertyName

        obj.type = 'success'
        _arr.push(obj)
        console.log(_arr)
      })
      this.tags = this.allselectitem = _arr

      
    },
    // 点击保存类目
    async savedate() {
      if (!this.form.name) {
        this.$message.warning('请输入分类名称');
        return;
      }
      if (!this.form.categoryNo) {
        this.$message.warning('请输入分类编码');
        return;
      }
      // 这个是进入编辑判断
      if (this.iseditsave) {
        console.log()
        console.log(this.alllevel)
        console.log('看看你是多少')
        if (this.alllevel == 1) {
          this.parentId = 0
        }
        const data = await editclass({
          parentId: this.parentId,
          //排序
          sort: this.form.sort,
          imgUrl: this.imgurl,
          level: this.alllevel,
          //随便ID
          creatorId: JSON.parse(localStorage.getItem('LOGIN_USER_INFO')).CREADTORID || '1',
          title: this.form.name,
          categoryNo: this.form.categoryNo,
          id: this.categoryid,
          categoryPropertyList: this.tags
        })
        console.log(data)
        if (data.code == 200) {
          this.$message.success('编辑保存成功！')
          this.$emit('refresh')
        }
      } else {
        console.log(this.tags)
        for (let i = 0; i < this.tags.length; i++) {
          this.tags[i].id = ''
        }
        if (!this.alllevel) {
          this.alllevel = 1
        }
        console.log('等级')
        // 这个是添加分类
        const data = await saveclass({
          parentId: this.parentId,
          sort: this.form.sort,
          imgUrl: this.imgurl,
          level: this.alllevel,
          //随便ID
          creatorId: JSON.parse(localStorage.getItem('LOGIN_USER_INFO')).CREADTORID || '1',
          title: this.form.name,
          categoryNo: this.form.categoryNo,
          categoryPropertyList: this.tags
        })
        console.log(data)
        if (data.code == 200) {
          console.log('添加')
          this.$message.success('添加成功')
          this.$emit('refresh', false)
          // this.issho = false
          // this.$emit('isflase', false)
          // this.$nextTick(() => {
          //   this.issho = true
          // })
        }
      }
    },
    aaa(str) {
      this.imgurl = str
      console.log(str)
    },
    // 删除图片后触发事件
    removeimg(data) {
      console.log(data)
      // 说明已经删除图片
      if (!data) {
        this.imgurl = ''
      }
    },
    // 编辑分类
    async editClass(data) {
      this.iseditsave = true
      this.isaddsave = false
      console.log(data)
      // console.log(678)
      // console.log(data.level)
      // 传给一个ID给定义的变量下面使用
      this.categoryid = data.id
      this.alllevel = data.level
      this.parentId = data.parentId
      this.form.sort = data.sort

      // console.log(this.$refs['classimg'].fileList)
      // this.$refs['classimg'].fileList = [
      //   {
      //     name: '图片',
      //     url: 'https://yswl-cloud-service.obs.cn-north-4.myhuaweicloud.com/' + data.imgurl
      //   }
      // ]
      // this.$nextTick(() => {
      //   this.imgurl = data.imgUrl
      // })

      // console.log(this.imgurl)
      // console.log('geile ')
      this.isshow = false
      this.title = '编辑'
      // 调用接口获取属性名所有数据显示在标签中
      const datas = await getbyid({
        id: data.id
      })
      if (datas.code == 200) {
        // console.log(datas.data.categoryPropertyList)
        // console.log(789)
        this.tags = this.allselectitem = datas.data.categoryPropertyList.map(item => {
          item.type = 'success'
          item.name = item.propertyName
          return item
        })
      }
      if (data.level == 1) {
        this.form.name = data.title
        this.form.categoryNo = data.categoryNo
        this.form.fathername = data.id
        this.ispic = false
        this.isbd = false
        this.$emit('hiddenadd', true)
        return
      }
      if (data.level == 2) {
        // 先清空图片数组
        this.$nextTick(() => {
          this.$refs['classimg'].handleRemoveempty()
        })
        this.ispic = true
        this.isbd = true
        this.form.name = data.title
        this.form.categoryNo = data.categoryNo
        this.hxtags(data.id)
        this.form.fathername = data.parentId
        this.$emit('hiddenadd', true)
      }
      if (data.level == 3) {
        // 先清空图片数组
        this.$nextTick(() => {
          this.$refs['classimg'].handleRemoveempty()
        })
        this.isbd = true
        this.ispic = true
        this.form.name = data.title
        this.form.categoryNo = data.categoryNo
        // this.imgurl = data.imgUrl
        //回显标签使用
        this.hxtags(data.id)
        // console.log('jajaj')
        this.$emit('hiddenadd', false)
      }
      // 图片赋值、
      if (!data.imgUrl) {
        return
      }
      this.$nextTick(() => {
        this.$refs['classimg'].fileList = [
          {
            name: '图片',
            url: 'https://yswl-cloud-service.obs.cn-north-4.myhuaweicloud.com/' + data.imgUrl
          }
        ]
      })
    },
    // 新增分类
    addClass(data) {
      console.log(6743)
      console.log(this.ispic)
      // this.removepic()
      this.$nextTick(() => {
        this.$refs['classimg'].handleRemoveempty()
      })
      this.disabled = true
      this.iseditsave = false
      this.isaddsave = true
      // 点击新增时统一把分类名称清空
      this.form.name = ''
      this.form.categoryNo = ''
      // 点击新增时统一把分类排序清空
      this.form.sort = ''
      // 点击新增时统一把上传图片清空
      // this.imgurl = ''
      // 点击新增时统一把选择属性清空
      this.tags = []
      // console.log(data)
      // console.log('最新的')
      this.categoryid = data.id
      this.isshow = true
      this.ispic = true
      //清空子组件里的filelist数组
      console.log(this.ispic)
      // console.log(this.$refs['classimg'])
      console.log(33333)
      // this.$refs['classimg'].handleRemoveempty()
      this.isbd = true
      this.title = '添加'
      // 如果点击的是第一类
      if (data.level == 1) {
        this.alllevel = 2
        this.parentId = data.id
      }
      if (data.level == 2) {
        this.form.fathername = data.id
        this.alllevel = 3
        this.parentId = data.id
      }
      if (this.title.level == 3) {
        this.form.fathername = data.id
        this.alllevel = 4
        this.parentId = data.id
      }
      console.log('我正在添加')
    },
    // 删除接口
    async removeClass(datas) {
      if (!datas) {
        this.$message.error('请选择要删除的分支')
        return
      }
      console.log(datas)
      this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = await removeclass({
            id: datas.id
          })
          if (data.code == 200) {
            this.$message.success('删除成功！')
          }
          this.$emit('refresh')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 显示弹窗里的数据表
    async getclassnames() {
      const data = await getclassname({
        status: 0
      })
      // console.log(data.data.list)
      // console.log(33333)
      this.gridData = data.data.list
      this.pagecount = data.data.total
      // 数据回显！！！！！！
      if (this.tags.length > 0) {
        this.$nextTick(function() {
          this.gridData.forEach(item => {
            for (let i = 0; i < this.tags.length; i++) {
              if (item.id == this.tags[i].propertyId) {
                this.$refs.multipleTable.toggleRowSelection(item) //选中
              }
            }
          })
        })
      }
    },
    // 回显属性值列表
    async hxtags(id) {
      const data = await getcontents({
        id: id
      })
      for (let i = 0; i < data.data.length; i++) {
        let valuesname = {}
        let randvalue = this.random(0, 3)
        valuesname.name = data.data[i].valueName
        // valuesname.id = data.data[i].id
        valuesname.valueName = data.data[i].valueName
        valuesname.type = this.colorArray[randvalue]
        this.tags.push(valuesname)
      }
      // console.log(data.data)
    },
    // 渲染左侧树
    async gettree() {
      const data = await getContenttree({})
      // console.log(data)
      this.options = data.data
    },
    // 选中选择属性触发
    selectad() {
      this.getclassnames()
      this.dialogTableVisible = true
    },
    // 删除标签删除属性值
    async handleClose(tag) {
      // console.log(tag)
      // console.log(232323)
      // console.log(this.tags)
      this.tags.splice(this.tags.indexOf(tag), 1)
    },
    // 清空删除上传组件中的所有图片
    removepic() {
      // console.log('删除', this.ispic, this.$refs['classimg'])
      //  this.$refs['classimg'].handleRemoveempty()
    },
    // 弹出框全选中后触发
    allselect(val) {
      // console.log(val)
      this.tags = []
      let _arr = []
      val.forEach(item => {
        let obj = {}
        obj.propertyId = item.id
        obj.name = obj.propertyName = item.propertyName

        obj.type = 'success'
        _arr.push(obj)
      })
      this.tags = this.allselectitem = _arr
    },
    //  分页接口点击
    async paging(pageNum) {
      console.log(pageNum)
      const data = await getclassname({
        pageSize: 10,
        pageNum: pageNum
        // name: this.storename
      })
      this.gridData = data.data.list
      this.pagecount = data.data.total
    }
  }
}
</script>

<style scoped>
.hx {
  height: auto;
  min-height: 40px;
  width: 40%;
  border: 1px solid #ccc;
  background-color: #fff;
  display: inline-block;
}
.grid-content .bdd ::v-deep .el-form-item__content {
  display: flex !important;
  align-items: center !important;
}
.tags {
  font-size: 14px;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: 400;
  color: #c9ccd3;
}
.fy {
  text-align: center;
  margin-top: 20px;
}
</style>
